package cn.tju.yanbo.commons.db;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.tju.yanbo.utils.AppConfig;


import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class AppDatabase {
    
    private static AppDatabase APP_DB = null;
    private Map<String, String> LUNAR_SONAR_CALENDAR_MAP = null;
    private SQLiteDatabase dbm = null;
    
    private AppDatabase() {}
    
    public static void startDBService(String dbFilePath) {
        if(APP_DB == null) {
            APP_DB = new AppDatabase();
            APP_DB.dbm = SQLiteDatabase.openOrCreateDatabase(dbFilePath, null);

            if(AppConfig.initDatabase() || !isDataLoaded()) {
                APP_DB.batchExecuteSql(DBUtils.TAL_CHONGSHA_SQL);
                APP_DB.batchExecuteSql(DBUtils.TAL_JISHI_SQL);
                APP_DB.batchExecuteSql(DBUtils.TAL_NONGLI_SQL);
                APP_DB.batchExecuteSql(DBUtils.TAL_YIJI_SQL);
            }
            APP_DB.loadNongLi();
        }
    }
    
    public static AppDatabase APP_DB() {
        if(APP_DB==null) throw new IllegalStateException("db service has not been started yet.");
        else return APP_DB;
    }
    
    public void batchExecuteSql(List<String> sqls) {
        for(String sql : sqls) {
            dbm.execSQL(sql);
        }
    }
    
    private static boolean isDataLoaded() {
        String sql = "SELECT COUNT(*)  as CNT FROM sqlite_master WHERE type=?";
        Cursor cursor = APP_DB.dbm.rawQuery(sql, new String[]{"table"});
        if(cursor.moveToNext()) {
            int tableCount = cursor.getInt(0);
            Log.i("startup", "table count is "+ tableCount);
            return tableCount==4;
        }
        return false;
    }
    
    private void loadNongLi() {
        String sql = "SELECT * FROM tbl_nongli";
        Cursor cursor = dbm.rawQuery(sql, new String[]{});
        
        LUNAR_SONAR_CALENDAR_MAP = new HashMap<String, String>();
        while(cursor.moveToNext()) {
            String sc = cursor.getString(0);
            String lc = cursor.getString(1);
            LUNAR_SONAR_CALENDAR_MAP.put(sc, lc);
        }
    }
    
    public String lunarCalendar(String sc) {
        return LUNAR_SONAR_CALENDAR_MAP.get(sc);
    }
}
